<template>
  <a-form class="smart-query-form" v-privilege="'oa:enterprise:query'">
    <a-row class="smart-query-form-row">
      <a-form-item label="应用名称" class="smart-query-form-item">
        <a-input style="width: 300px" v-model:value="queryForm.appName" placeholder="请输入应用名称" />
      </a-form-item>
      <a-form-item label="协议" class="smart-query-form-item">
        <a-select v-model:value="queryForm.protocol" style="width: 300px" placeholder="请选择协议" :options="protocolOption"></a-select>
      </a-form-item>
      <a-form-item label="分类" class="smart-query-form-item">
        <a-select v-model:value="queryForm.category" style="width: 300px" placeholder="请选择协议" :options="FindList"></a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false" :hoverable="true">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item v-for="(item, index) in addType" :key="index + 1" @click="handleMenuClick(item, index + 1)">
                <UserOutlined />
                {{ item.name }}
              </a-menu-item>
            </a-menu>
          </template>
          <a-button type="primary">
            新增
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <a-button type="primary" danger @click="handleDelete(null)">删除</a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.APPLICATIONMANAGEMENT.ID" :refresh="ajaxQuery" />
      </div>
    </a-row>
    <a-table
      size="small"
      rowKey="id"
      :dataSource="tableData"
      :columns="columns"
      :pagination="false"
      :loading="tableLoading"
      bordered
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
    >
      <template #bodyCell="{ column, record, text, index }">
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'iconBase64'">
          <img :src="record.iconBase64" alt="" style="width: 40px" />
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-switch v-model:checked="record.status" :checkedValue="1" :unCheckedValue="0" :disabled="true">
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
          {{ record.status }}
        </template>
        <template v-if="column.dataIndex === 'category'">
          {{ FindList.filter((i) => i.value === record.category).length ? FindList.filter((i) => i.value === record.category)[0].label : '' }}
        </template>
      </template>
      <template #operation="{ record }">
        <!-- <a-button type="text" style="margin-right: 10px;">编辑</a-button> -->
        <a-button size="small" type="link" style="margin-right: 10px" @click="upData(record)">编辑</a-button>
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item :key="1">
                <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button type="link" size="small">
            更多
            <DownOutlined />
          </a-button>
        </a-dropdown>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNumber"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="ajaxQuery"
        @showSizeChange="ajaxQuery"
        :show-total="(total) => `共${total}条`"
      />
    </div>
    <!-- <EnterpriseOperate ref="operateRef" @refresh="ajaxQuery" /> -->
  </a-card>
  <ApplicationForm ref="applicationFormRef" />
  <AppOauth20DetailsEditerComponent ref="AppOauth20DetailsEditerComponentRef" @childEvent="ajaxQuery" />
  <AppSaml20DetailsEditerComponent ref="AppSaml20DetailsEditerComponentRef" @childEvent="ajaxQuery"/>
  <CAS ref="casref" @childEvent="ajaxQuery"/>
  <JWT ref="jwtref" @childEvent="ajaxQuery"/>
  <TokenBased ref="tokenbasedref" @childEvent="ajaxQuery"/>
  <Formbased ref="formbasedref" @childEvent="ajaxQuery"/>
  <Extendapi ref="extendapiref" @childEvent="ajaxQuery"/>
  <Basic ref="basicref" @childEvent="ajaxQuery"/>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { useRouter } from 'vue-router';
// import EnterpriseOperate from './components/enterprise-operate-modal.vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api';
import ApplicationForm from './components/form.vue';
import AppOauth20DetailsEditerComponent from './components/OAuth_v2.0.vue';
import AppSaml20DetailsEditerComponent from './components/saml20.vue';
import CAS from './components/cas.vue';
import Basic from './components/basic.vue';
import JWT from './components/jwt.vue';
import TokenBased from './components/TokenBased.vue';
import Formbased from './components/formbased.vue';
import Extendapi from './components/extendapi.vue';
// --------------------------- 企业表格 列 ---------------------------
const addType = ref([
  { name: 'OAuth2.x' },
  { name: 'SAML2.0' },
  { name: 'CAS认证' },
  { name: 'JWT令牌' },
  { name: '令牌认证' },
  { name: '表单认证' },
  { name: 'API扩展认证' },
  { name: '基本登录' },
]);
const statusOptions = ref([
  { label: 'ACTIVE', value: 1 },
  { label: 'INACTIVE', value: 2 },
  { label: 'DISABLED', value: 4 },
  { label: 'LOCK', value: 5 },
  { label: 'UNLOCK', value: 6 },
  { label: 'DELETE', value: 9 },
]);
const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    width: 50,
    align: 'center',
  },
  {
    title: '图标',
    dataIndex: 'iconBase64',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
  },
  {
    title: '协议',
    dataIndex: 'protocol',
  },
  {
    title: '分类',
    dataIndex: 'category',
    // fixed: 'right',
  },
  {
    title: '排序',
    dataIndex: 'sortIndex',
  },
  {
    title: '状态',
    dataIndex: 'status',
    // fixed: 'right',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 150,
    slots: { customRender: 'operation' },
  },
]);

const protocolOption = ref([
  { label: 'ALL', value: '' },
  { label: 'OAuth_v2.0', value: 'OAuth_v2.0' },
  { label: 'OAuth_v2.1', value: 'OAuth_v2.1' },
  { label: 'OpenID Connect v1.0', value: 'OpenID Connect v1.0' },
  { label: 'SAML v2.0', value: 'SAML v2.0' },
  { label: 'CAS', value: 'CAS' },
  { label: 'JWT', value: 'JWT' },
  { label: 'Token Based', value: 'Token Based' },
  { label: 'Form Based', value: 'Form Based' },
  { label: 'Extend API', value: 'Extend API' },
  { label: 'Basic', value: 'Basic' },
]);
// --------------------------- 查询 ---------------------------

const queryFormState = {
  pageNumber: 1,
  pageSize: PAGE_SIZE,
  searchCount: true,
  appName: '',
  category: '',
  protocol: '',
};
const queryForm = reactive({ ...queryFormState });
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref(0);

// 日期选择
const searchDate = ref();

function dateChange(dates, dateStrings) {
  queryForm.startTime = dateStrings[0];
  queryForm.endTime = dateStrings[1];
}
// 查询
function onSearch() {
  queryForm.pageNumber = 1;
  ajaxQuery();
}
// 重置查询
function resetQuery() {
  searchDate.value = [];
  Object.assign(queryForm, queryFormState);
  ajaxQuery();
}
function dateToSeconds(dateStr) {
  if (dateStr == '') {
    return '';
  }
  let date = new Date(dateStr);
  return date.getTime() / 1000;
}
// 列表数据获取
async function ajaxQuery() {
  try {
    tableLoading.value = true;
    let responseModel = await applicationManagementApi.getFetch(queryForm);
    const list = responseModel.data.rows.map((i, index) => {
      i['key'] = index;
      return i;
    });
    total.value = responseModel.data.records;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// --------------------------- 增加、修改、详情 ---------------------------

let router = useRouter();
const applicationFormRef = ref(null);
const AppOauth20DetailsEditerComponentRef = ref(null);
const AppSaml20DetailsEditerComponentRef = ref(null);
const jwtref = ref(null);
const casref = ref(null);
const tokenbasedref = ref(null);
const formbasedref = ref(null);
const extendapiref = ref(null);
const basicref = ref(null);
function handleMenuClick(item, key) {
  console.log(item.name);
  
  switch (item.name) {
    case 'OAuth2.x': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(null, key, '新增');
      break;
    }
    case 'OAuth_v2.0': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(null, key, '新增');
      break;
    }
    case 'OAuth_v2.1': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(null, key, '新增');
      break;
    }
    case 'OpenID_Connect_v1.0': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(null, key, '新增');
      break;
    }
    case "SAML2.0": {
      AppSaml20DetailsEditerComponentRef.value.showDrawer(null, key, '新增');
      break;
    }
    case 'CAS认证': {
      casref.value.showDrawer(null, key, '新增');
      break;
    }
    case 'JWT令牌': {
      jwtref.value.showDrawer(null, key, '新增');
      break;
    }
    case '令牌认证': {
      tokenbasedref.value.showDrawer(null, key, '新增');
      break;
    }
    case '表单认证': {
      formbasedref.value.showDrawer(null, key, '新增');
      break;
    }
    case 'API扩展认证': {
      extendapiref.value.showDrawer(null, key, '新增');
      break;
    }
    case '基本登录': {
      basicref.value.showDrawer(null, key, '新增');
      break;
    }
    default: {
      basicref.value.showDrawer(null, key, '新增');
      break;
    }
  }
  return;

  applicationFormRef.value.showDrawer(null, key.key, '新增');
}
function upData(record) {
  console.log(record.protocol);
  
  switch (record.protocol) {
    case 'OAuth2.x': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'OAuth_v2.0': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'OAuth_v2.1': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'OpenID_Connect_v1.0': {
      AppOauth20DetailsEditerComponentRef.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'SAML_v2.0': {
      AppSaml20DetailsEditerComponentRef.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'CAS': {
      casref.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'JWT': {
      jwtref.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'Token_Based': {
      tokenbasedref.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'Form_Based': {
      formbasedref.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'Extend_API': {
      extendapiref.value.showDrawer(record, 0, '编辑');
      break;
    }
    case 'Basic': {
      basicref.value.showDrawer(record, 0, '编辑');
      break;
    }
  }
  return;
  applicationFormRef.value.showDrawer(record, 0, '编辑');
}
function handleDelete(value) {
  Modal.confirm({
    title: () => '确定要删除吗?',
    content: () => '删除后不可恢复',
    onOk() {
      if (value) {
        applicationManagementApi.delete({ ids: value.id }).then((res) => {
          if (res.code === 0) {
            message.success('删除成功！');
            ajaxQuery();
          }
        });
      } else if (selectedRowKeyList.value.length) {
        applicationManagementApi.delete({ ids: selectedRowKeyList.value.join(',') }).then((res) => {
          if (res.code === 0) {
            message.success('删除成功！');
            ajaxQuery();
          }
        });
      }
    },
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() {},
  });
}

// 获取分类下拉
const FindList = ref([]);
async function getFindList() {
  try {
    let res = await applicationManagementApi.queryFindList();
    FindList.value = res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    FindList.value.unshift({ label: 'ALL', value: '' });
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
  }
}
// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}
onMounted(() => {
  ajaxQuery();
  getFindList();
});
</script>